import Message from '../component/Message'
import copyToClipboard from 'copy-to-clipboard'
import { isMobile } from './check';

// eslint-disable-next-line @typescript-eslint/no-var-requires
const { version, buildNumber } = require('../../package.json')
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
window.version = version;
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
window.buildNumber = buildNumber;

export const copy = (str?: string, noti = true) => {
    if (!str) {
        noti && Message.error('copy failed')
        return
    }

    copyToClipboard(str);
    noti && Message.success('copy success')
}

export const randomString = (length?: number) => {
    const l = length || 16;
    const t = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678',
        a = t.length
    let n = '';
    for (let i = 0; i < l; i++) n += t.charAt(Math.floor(Math.random() * a));
    return n
}

export const getCookie = (n: string): string => {
    const name = n + '=';
    const ca = document.cookie.split(';');
    for (let i = 0; i < ca.length; i++) {
        const c = ca[i].trim();
        if (c.indexOf(name) === 0) return c.substring(name.length, c.length);
    }
    return '';
}

export const setIntervalImmediately = (callback: () => void, ms?: number | undefined): NodeJS.Timeout => {
    callback();
    return setInterval(callback, ms)
}

export const isValidKey = (
    key: string | number | symbol,
    object: object
): key is keyof typeof object => {
    return key in object;
}

export const formatBase64Image = (image: string, type?: 'png' | 'jpge'): string | undefined => {
    if (!image) {
        return
    }

    if (image.startsWith('data:image')) {
        return image
    }
    return `data:image/${type || 'png'};base64,${image}`
}

export const versionInfo = (): string => {
    return `${version}.${buildNumber}`
}

export const disableSwipdown = () => {
    if (isMobile()) {
        // disable telegram mini app close when swipe down
        resetWindowPosition()
    }
}

export const resetWindowPosition = (animation?: boolean) => {
    const overflow = 100
    document.body.style.overflowY = 'hidden'
    document.body.style.marginTop = `${overflow}px`
    document.body.style.height = window.innerHeight + overflow + 'px'
    document.body.style.paddingBottom = `${overflow}px`
    if (animation) {
        window.scrollTo({
            left: 0,
            top: overflow,
            behavior: 'smooth'
        })
        return
    }

    window.scrollTo(0, overflow)
}